#include "list_sorter.h"

bool comp(UnitInfo* i, UnitInfo* j) 
{ 
    return (i->weight() > j->weight()); 
}

int ListSorter::SortList(MergeList* mergeList[], int32_t listNum, MergeList* sortList)
{
    m_unitVec.clear();
    UnitInfo* unit = NULL;
    for(int32_t i = 0; i < listNum; ++i)
    {
        for(int j = 0; j < mergeList[i]->unit_size(); ++j)
        {
            unit = mergeList[i]->mutable_unit(j);
            if(unit->id() != -1)
            {
                m_unitVec.push_back(unit);
            }
        }
    }
    int num = MAX_KEEP_NUM > m_unitVec.size() ?  m_unitVec.size() : MAX_KEEP_NUM;
    nth_element(m_unitVec.begin(), m_unitVec.begin()+num, m_unitVec.end(), comp);
    sort(m_unitVec.begin(), m_unitVec.begin()+num, comp);
    sortList->Clear();
    for(int i = 0; i < num; ++i)
    {
        unit = sortList->add_unit();
        unit->set_id(-1);
    }
    for(int i = 0; i < num; ++i)
    {
        if(m_unitVec[i]->pos() != -1 && m_unitVec[i]->pos() < num)
        {
            unit = sortList->mutable_unit(m_unitVec[i]->pos());
            *unit = *m_unitVec[i];
        }
    }
    int idx = 0;
    for(int i = 0; i < num; ++i)
    {
        if(m_unitVec[i]->pos() != -1)
            continue;
        unit = sortList->mutable_unit(idx);
        while(unit->id() != -1)
        {
            ++idx;
            unit = sortList->mutable_unit(idx);
        }
        *unit = *m_unitVec[i];
    }
    return num;
}


















/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
